<template lang="html">
  <div class="article-div">
<!--    <el-card>-->
<!--      <el-button type="primary" @click="articleDialog('post')">添加文章</el-button>-->
      <el-table
        class="articleTab"
        :data="articleTab"
        stripe
        border
        style="width: 100%;"
      >
        <el-table-column prop="title" label="文章标题" />
        <el-table-column prop="content" label="文章内容" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="articleDialog('put',scope.row)"
            >编辑</el-button>
            <el-button
              type="warning"
              @click="deleteArticle(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
<!--    </el-card>-->
<!--    <el-dialog title="用户组编辑" :visible.sync="articleDiaIsShow" class="diaForm">-->
<!--      <el-form-->
<!--        ref="articleForm"-->
<!--        :model="articleForm"-->
<!--        :rules="articleRules"-->
<!--        label-width="140px"-->
<!--      >-->
<!--        <el-form-item label="标题" prop="title">-->
<!--          <el-input-->
<!--            v-model="articleForm.title"-->
<!--            type="text"-->
<!--            placeholder="请输入要添加的文章标题"-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="内容" prop="content">-->
<!--          <editor-->
<!--            id="articleEditor"-->
<!--            v-model="articleForm.content"-->
<!--            :init="editorInit"-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button-->
<!--            type="primary"-->
<!--            @click="editArticle()"-->
<!--          >确认</el-button>-->
<!--          <el-button @click="articleDiaIsShow = false">取消</el-button>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--    </el-dialog>-->
    <pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getArticleList" />
  </div>
</template>

<script>
// import tinymce from 'tinymce/tinymce'
import Pagination from '@/layout/components/Pagination'
import Editor from '@tinymce/tinymce-vue'
// import 'tinymce/themes/silver'
// import 'tinymce/icons/default/icons' // 解决了icons.js 报错Unexpected token '<'
// // 编辑器插件plugins
// // 更多插件参考：https://www.tiny.cloud/docs/plugins/
// import 'tinymce/plugins/image'// 插入上传图片插件
// import 'tinymce/plugins/media'// 插入视频插件
// import 'tinymce/plugins/table'// 插入表格插件
// import 'tinymce/plugins/lists'// 列表插件
// import 'tinymce/plugins/wordcount'// 字数统计插件
export default {
  name: 'Article',
  components: {
    'editor': Editor,
    Pagination
  },
  data() {
    return {
      listQuery: {
        page: 1,
        limit: 20
      },
      total: 0,
      articleTab: [],
      articleEditType: 'post',
      articleDiaIsShow: false,
      articleForm: {
        id: '',
        title: '',
        content: ''
      },
      articleRules: {
        mobile_number: [{
          required: true,
          trigger: 'blur'
        }],
        password: [{
          required: true,
          trigger: 'blur'
        }]
      },
      loading: false,
      editorInit: {
        selector: '#articleEditor',
        base_url: 'static/js/tinymce5.4.1/',
        // skin_url: 'static/js/tinymce5.4.1/langs/zh_CN.js',
        height: 500,
        language: 'zh_CN',
        images_upload_handler: function uploadHandler(blobInfo, success, failure, progress) {
          var blobInfoDetail = blobInfo.blob()
          var valid_extensions = ['png', 'jpg', 'gif']
          var ext, extensions

          extensions = {
            'image/jpeg': 'jpg',
            'image/jpg': 'jpg',
            'image/gif': 'gif',
            'image/png': 'png'
          }

          ext = extensions[blobInfoDetail.type.toLowerCase()] || 'dat'
          // add your extension test here.
          if (valid_extensions.indexOf(ext) === -1) {
            failure('Invalid extension')
            return
          }
          if (blobInfoDetail.size && blobInfoDetail.size > 10000000) {
            failure('图片大小不能超过10Mb')
            return
          }

          var xhr, formData
          xhr = new XMLHttpRequest()
          xhr.withCredentials = false
          xhr.open('POST', process.env.VUE_APP_BASE_API + '/media/image')
          xhr.upload.onprogress = function(e) {
            progress(e.loaded / e.total * 100)
          }
          xhr.onload = function() {
            var code = xhr.status.toString()
            var startChar = code.charAt(0)
            var json = JSON.parse(xhr.responseText)
            if (startChar === '2') {
              success(json.data[0])
            } else {
              failure(json.msg)
            }
          }
          xhr.onerror = function() {
            failure('上传错误. 代码: ' + xhr.status)
          }
          formData = new FormData()
          formData.append('image1', blobInfo.blob(), blobInfo.filename())
          xhr.send(formData)
        },
        plugins: [
          'advlist autolink lists link image charmap print preview anchor',
          'searchreplace visualblocks code fullscreen',
          'insertdatetime media table paste code help wordcount'
        ],
        toolbar: 'undo redo|formatselect|bold italic backcolor|alignleft aligncenter alignright alignjustify |bullist numlist outdent indent|removeformat |image|help'
      }
    }
  },
  watch: {},
  created() {
    this.init()
  },
  mounted() {
    this.$nextTick(() => {
      // window.tinymce.baseURL = window.location.origin + '/static/js/tinymce5.4.1'
    })
    // tinymce.init({})
  },
  methods: {
    init() {
      this.$nextTick(() => {
        this.$set(this.articleForm, 'title', '示例标题')
        this.$set(this.articleForm, 'content', '暂无')
      })
      this.getArticleList()
    },
    getArticleList() {
      this.loading = true
      this.$store.dispatch('article/getArticleList').then(res => {
        this.articleTab = res.data
        this.loading = false
      }).catch(err => {
        // console.log(err, 183)
        this.$message({
          type: 'error',
          message: err.data.msg
        })
      })
    },
    editArticle() {
      var data = {}
      if (this.articleEditType === 'put') {
        data.article_id = this.articleForm.id
        data.article_title = this.articleForm.title
        data.article_content = this.articleForm.content
        this.$store.dispatch('article/putArticle', data).then((res) => {
          this.getArticleList()
          this.loading = false
          this.articleDiaIsShow = false
          this.$message({
            type: 'success',
            message: res.msg
          })
        }).catch(() => {
          this.loading = false
          return false
        })
      } else if (this.articleEditType === 'post') {
        this.$refs['articleForm'].validate(valid => {
          if (valid) {
            data.article_title = this.articleForm.title
            data.article_content = this.articleForm.content
            this.$store.dispatch('article/postArticle', data).then((res) => {
              this.getArticleList()
              this.loading = false
              this.articleDiaIsShow = false
              this.$message({
                type: 'success',
                message: res.msg
              })
            }).catch(() => {
              this.loading = false
              return false
            })
          }
        })
      }
    },
    deleteArticle(article_id) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // console.log(article_id)
          this.$store.dispatch('article/deleteArticle', {
            article_id
          }).then((res) => {
            this.getArticleList()
            this.loading = false
            this.articleDiaIsShow = false
            this.$message({
              type: 'success',
              message: res.msg
            })
          }).catch(() => {
            this.loading = false
            return false
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    articleDialog(type, row) {
      this.articleDiaIsShow = true
      switch (type) {
        case 'post':
          this.articleEditType = 'post'
          break
        case 'put':
          this.articleEditType = 'put'
          this.$nextTick(() => {
            this.$set(this.articleForm, 'id', row.id)
            this.$set(this.articleForm, 'title', row.title)
            this.$set(this.articleForm, 'content', row.content)
          })
          break
        default:
      }
    }
  }
}
</script>

<style scoped>
.article-div {}

.tinymce-container {
  position: relative;
  line-height: normal;
}

.tinymce-container>>>.mce-fullscreen {
  z-index: 10000;
}

.tox,
.tox-tinymce-aux,
.tox-silver-sink {
  z-index: 10000;
}
</style>
